package com.example.demo.service.impl;

import com.example.demo.service.EmailService;
import com.example.demo.service.RedisService;
import com.example.demo.util.EmailTextUtil;
import com.example.demo.util.RandomUtil;
import jakarta.annotation.Resource;
import lombok.val;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

@Service
public class EmailServiceImpl implements EmailService {

    @Value("${spring.mail.username}")
    private String EMAIL_USERNAME;
    @Resource
    private JavaMailSender javaMailSender;
    @Resource
    private RedisService redisService;
    /**
     * 发送模板模板
     *
     * @param email 收件人邮箱
     */
    public boolean sendMailForTemplateEngine(String email, int k) {
        try {
            SimpleMailMessage mailMessage = new SimpleMailMessage();
            mailMessage.setFrom(EMAIL_USERNAME);//发送者
            mailMessage.setTo(email);//接收者
            mailMessage.setSubject("diary");//邮件标题
            val random1 = RandomUtil.random1(6);
            val emailText = EmailTextUtil.emailText(random1, k);
            mailMessage.setText(emailText);//邮件内容
            String REDIS_AUTH = "AUTH" + k + email;
            this.redisService.setExpire(REDIS_AUTH,random1,60*10);
            this.javaMailSender.send(mailMessage);//发送邮箱
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
